package com.chalmers.foa.gamemodel.gameobjects.obstacles.impl;

import android.graphics.Bitmap;
import android.graphics.Point;

import com.chalmers.foa.gamehandlers.impl.CollisionHandler;
import com.chalmers.foa.gamehandlers.impl.PhysicsHandler;
import com.chalmers.foa.gamemodel.gameobjects.GameObjectBitmapAdapter;
import com.chalmers.foa.gamemodel.gameobjects.IGameObject;
import com.chalmers.foa.gamemodel.gameobjects.obstacles.IMovableObstacle;
import com.chalmers.foa.gamemodel.gameobjects.other.impl.Enemy;
import com.chalmers.foa.gamemodel.gameobjects.other.impl.PlayerObject;
import com.chalmers.foa.util.NewList;

public class GravitableObstacle extends GameObjectBitmapAdapter implements
		IMovableObstacle {

	private Point velocity;
	private int maxSpeed;
	private NewList collidingObjects;
	private IGameObject collidingObject;

	public GravitableObstacle(Bitmap bitmap) {
		this(new Point(0,0),bitmap,0,-1);
	}

	public GravitableObstacle(Point _position,Bitmap _bitmap,int layer,int bound){
		super(_bitmap,_position,layer,bound, true, false, true, false);
		velocity = new Point(0,0);
		maxSpeed = 16;
		collidingObjects = new NewList(10);
	}
	
	private void adjustSpeedToMaxSpeed() {
		if(velocity.y > maxSpeed)
			velocity.y = maxSpeed;
		else if(velocity.y < -maxSpeed)
			velocity.y = -maxSpeed;
	}
	
	public void update() {
		move();
	}
	
	private void move() {
		PhysicsHandler.getInstance().applyGravitationToOffset(velocity);
		adjustSpeedToMaxSpeed();
		CollisionHandler.getInstance().objectsCollidingWithObject(this, velocity, collidingObjects);
		if(collidingObjects != null)
			for(int i = 0; i < collidingObjects.getSize(); i++) {
				collidingObject = collidingObjects.getObjectAt(i);
				if(collidingObject.isAlive()) {
					if(collidingObject instanceof PlayerObject || collidingObject instanceof Enemy) { //Makes sure that this object pushes the player and enemies
						if(collidingObject.getPosition().x + collidingObject.getWidth() >= getPosition().x &&
								collidingObject.getPosition().x <= getPosition().x + getWidth() && collidingObject.isAlive()) {
							CollisionHandler.getInstance().alignOffsetToObject(this, velocity, collidingObject);
						}
					}
				}
			}
		velocity.x = 0;
		CollisionHandler.getInstance().validateOffset(this, velocity);
		translate(velocity);
	}

	
	@Override
	public Point getVelocity() {
		return velocity;
	}

	@Override
	public void setVelocity(Point velocity) {
		this.velocity = new Point(velocity);

	}

}
